
<template> 
  <div class="main">
     <h2>大数计算</h2>
     <h6>采用big.js 对超出js一般运算的数据进行运算</h6>
     <div class="area">
       <div class="left">
           <textarea  v-model="textareaLeft" @change="calc"  @keyup="format" @keyup.enter="calc"></textarea>
       </div>
       <div class="right">
          <textarea v-model="textareaRight" ></textarea>
       </div>
     </div>
     <div class="area">
       <div class="left">
           <textarea  v-model="textareaLeft2" @change="calc2"  @keyup="calc2" ></textarea>
       </div>
       <div class="right">
          <textarea v-model="textareaRight2" ></textarea>
       </div>
     </div>
  </div>
</template>
<script > 
import Big from 'big.js'
window.Big = Big
export default {
   data(){
     return {
       textareaLeft:'3.33 * 3',textareaRight:"",
       textareaLeft2:'Big(1).plus(Big(2)).times(Big(3)).div(Big(4)).minus(Big(1))',textareaRight2:"",
     }
   },
   mounted(){
      console.log(this.textareaLeft,this.textareaRight)
      this.calc()
   },
   methods:{
     format(e){ 
       if(e.key == "+" || e.key == "-" || e.key == "*" || e.key == "/" ){
         var all= this.textareaLeft.split("")
         all.pop() 
         all = all.join("")
         this.textareaLeft = all + " " + e.key + " "
       }
     },
     calc2(){ 
       var all = this.textareaLeft2.split("\n")
        all = all.map(e=>{
           try{
               return eval(e)
           }catch(err){
               return e
           }
        })
        this.textareaRight2 = all.join("\n")
     },
     calc(){ 
       var th = this; 
       console.log(this.textareaLeft,this.textareaRight)
       var all = this.textareaLeft.split("\n")
       console.log(all)
       
       all = all.map(e=>{
         e = e.trim()
         var arr = e.split(" ").map(e=>e.trim())
         if(arr.length == 3) {
           return th.calcTwo(arr[0],arr[1],arr[2])
         }else{
           return e
         }
       })
      console.log(all)
       this.textareaRight = all.join("\n")
     },
     calcTwo(left,flag,right){  
       try{
         switch(flag){
          case "+" :  return Big(left).plus(Big(right)).toFixed();
          case "-" :  return Big(left).minus(Big(right)).toFixed();
          case "*" :  return Big(left).times(Big(right)).toFixed();
          case "/" : if(parseFloat(right)==0) return "div zero error";  return Big(left).div(Big(right)).toFixed();
          default: return [left,flag,right].join(" ")
         }
       }catch(e){

       }
     },
   }
}
</script>


<style>
 .area{
   display: flex;
 }
 .left{ width: 60%;}
 .right{ width: 40%;}
 textarea{ width: 100%; height: 40vh;}
</style>
